<template>
  <div class="user-manage-wrapper">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="用户名">
        <el-input v-model="formInline.userNameLike" placeholder="请输入用户名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchSource">查询</el-button>
        <el-button type="primary" @click="popNewAddDialog">新增用户</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="tableData" ref="multipleTable" v-loading="loading" stripe>
      <el-table-column label="序号" width="50">
        <template slot-scope="scope">{{ scope.$index + startNum + 1 }}</template>
      </el-table-column>
      <el-table-column label="用户名" prop="userName"></el-table-column>
      <el-table-column label="真实姓名" prop="realName"></el-table-column>
      <el-table-column label="性别" prop="sex">
        <template slot-scope="scope">{{convertKeyToVal(scope.row.sex, sexOpts)}}</template>
      </el-table-column>
      <el-table-column label="手机号码" prop="mobilePhone"></el-table-column>
      <el-table-column label="用户类型" prop="userType">
        <template slot-scope="scope">{{convertKeyToVal(scope.row.userType, userTypeOpts)}}</template>
      </el-table-column>
      <el-table-column label="角色" prop="roles">
        <template slot-scope="scope">{{transformField(scope.row.roles)}}</template>
      </el-table-column>
      <el-table-column label="操作" min-width="100px">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" icon="el-icon-view" @click="viewDetail(scope.row.userId);roleChange(scope.row)">查看</el-link>&nbsp;
          <el-link type="success" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.userId);roleChange(scope.row)">编辑</el-link>&nbsp;
          <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.userId)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="paging-self"
      background
      :current-page.sync="currentPage"
      @current-change="pageChange"
      layout="total, prev, pager, next"
      :total="totalCount">
    </el-pagination>
    <!-- 对话框 开始 -->
    <el-dialog title="用户" :visible.sync="dialogFormVisible" width="660px" @closed="closeDialog" :close-on-click-modal="false">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog" label-width="108px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="dialogForm.userName" placeholder="请输入用户名" autocomplete="off" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="dialogForm.realName" placeholder="请输入真实姓名" autocomplete="off" maxlength="30"></el-input>
        </el-form-item>
        <!-- <el-form-item label="昵称" prop="nickName">
          <el-input v-model="dialogForm.nickName" placeholder="请输入昵称" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dialogForm.email" placeholder="请输入邮箱" autocomplete="off" maxlength="30"></el-input>
        </el-form-item>
        <!-- <el-form-item label="电话" prop="telephone">
          <el-input v-model="dialogForm.telephone" placeholder="请输入电话" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="手机号码" prop="mobilePhone">
          <el-input v-model="dialogForm.mobilePhone" placeholder="请输入手机号码" autocomplete="off" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogMode===CNST.ADDNEW_MODE" label="密码" prop="password">
          <el-input v-model="dialogForm.password" placeholder="请输入密码" autocomplete="off" type="password" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogMode===CNST.ADDNEW_MODE" label="确认密码" prop="repassword">
          <el-input v-model="dialogForm.repassword" placeholder="请输入密码" autocomplete="off" type="password" maxlength="30"></el-input>
        </el-form-item>
        <!-- <el-form-item label="密码盐" prop="passwordSalt">
          <el-input v-model="dialogForm.passwordSalt" placeholder="请输入密码盐" autocomplete="off"></el-input>
        </el-form-item> -->
        <!-- <el-form-item label="头像" prop="photo">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-input v-model="dialogForm.photo" placeholder="请输入头像" autocomplete="off"></el-input>
        </el-form-item> -->
        <el-form-item label="性别" prop="sex">
          <el-select v-model="dialogForm.sex" placeholder="请选择性别" clearable>
            <el-option label="男" value="M"></el-option>
            <el-option label="女" value="F"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="dialogForm.birthday"
            type="date"
            placeholder="请选择选择出生日期" clearable>
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="用户类型" prop="userType">
          <el-select v-model="dialogForm.userType" placeholder="请选择用户类型" clearable>
            <el-option label="普通用户" value="P"></el-option>
            <el-option label="管理员" value="G"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item v-if="superAdmin!=='superAdmin'" label="角色" prop="roleIds">
          <el-select v-model="dialogForm.roleIds" placeholder="请选择角色" multiple clearable>
            <el-option
             v-for="(item) in roleTypeOpts"
             :key="item.roleId"
             :label="item.roleName"
             :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="启用禁用状态" prop="userStatus">
          <el-select v-model="dialogForm.userStatus" placeholder="请选择启用禁用状态" clearable>
            <el-option label="启用" value="Q"></el-option>
            <el-option label="禁用" value="J"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import CryptoJS from "crypto-js"
import {
  getUserList,
  addUser,
  getUserDetail,
  updateUser,
  deleteUser,
  getRoleList
} from '@/api/systemManage'
import { deepClone, convertDateToString } from '@/utils'

var validateCellphone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号码'))
  } else if (!(/^1[3456789]\d{9}$/.test(value))) {
    callback(new Error('手机号码格式错误'))
  } else {
    callback()
  }
}

var validateEmail = (rule, value, callback) => {
  if (value === '') {
    callback()
  } else if (!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value))) {
    callback(new Error('邮箱格式错误'))
  } else {
    callback()
  }
}

export default {
  name: 'UserManage',
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.dialogForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      superAdmin: '',
      sexOpts: [
        {
          dictoryName: '男',
          dictoryValue: 'M'
        },
        {
          dictoryName: '女',
          dictoryValue: 'F'
        }
      ],
      userTypeOpts: [
        {
          dictoryName: '普通用户',
          dictoryValue: 'P'
        },
        {
          dictoryName: '管理员',
          dictoryValue: 'G'
        }
      ],
      roleTypeOpts: [],
      imageUrl: '',
      uploadUrl: `${process.env.VUE_APP_BASE_API}/upload/uploadFile`,
      formInline: {
        userNameLike: ''
      },
      tableData: [],
      loading: false,
      dialogMode: '',
      dialogFormVisible: false,
      dialogForm: {
        userName: '',
        realName: '',
        nickName: '',
        email: '',
        telephone: '',
        mobilePhone: '',
        password: '',
        repassword: '',
        passwordSalt: '',
        college: '',
        education: '',
        sex: '',
        birthday: '',
        userType: 'G',
        roleIds: [],
        areaId: '',
        userStatus: ''
      },
      rules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        repassword: [{ required: true, validator: validatePass2, trigger: 'blur' }],
        userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
        email: [{ required: false, validator: validateEmail, trigger: 'blur' }],
        mobilePhone: [{ required: true, validator: validateCellphone, trigger: 'blur' }]
      },
      startNum: 0,
      curId: '',
      totalCount: 0, // 总共多少条
      currentPage: 1 // 分页当前页
    }
  },
  methods: {
    convertKeyToVal (code, arr) {
      arr = Array.isArray(arr) ? arr : []
      let resArr = arr.filter((item) => {
        return item.dictoryValue === code
      })
      if (resArr.length === 0) {
        return ''
      }
      return resArr[0].dictoryName
    },
    transformField(fieldArr) {
      return fieldArr.map((obj) => {
        return obj.roleName
      }).join(',')
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(file)
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(this.imageUrl)
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },
    async getListAndShow () {
      try {
        this.loading = true
        let requestData = {
          page: this.currentPage,
          pageSize: 10,
          userNameLike: this.formInline.userNameLike.trim()
        }
        var res = await getUserList(requestData)
        this.tableData = res.data.queryResult
        this.totalCount = res.data.totalCount
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    searchSource () {
      this.currentPage = 1
      this.getListAndShow()
    },
    pageChange (curPage) {
      this.currentPage = curPage
      this.startNum = (curPage - 1) * 10
      this.getListAndShow()
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
    },
    roleChange (data) {
      let roleAdmin = data.roles.filter(item => item.roleType === 'superAdmin')
      if (roleAdmin.length === 0) {
        this.superAdmin = ''
      } else {
        this.superAdmin = 'superAdmin'
      }
    },
    viewDetail (userId) {
      this.dialogMode = this.CNST.READ_MODE
      this.dialogFormVisible = true
      getUserDetail({ userId }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    editDetail (userId) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = userId
      getUserDetail({ userId }).then((res) => {
        this.showToDialog(res.data)
      })
    },
    deleteDetail (userId) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteUser({ userId }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getListAndShow()
        })
      })
    },
    showToDialog (data) {
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key) || key === 'roles') {
          if (key === 'roles') {
            this.$set(this.dialogForm, 'roleIds', data[key].map((item) => {
              return item.roleId
            }))
          } else {
            this.dialogForm[key] = data[key]
          }
        }
      }
    },
    closeDialog () {
      this.superAdmin = ''
      this.dialogMode = ''
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    },
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          let requestData = deepClone(this.dialogForm)
          requestData.roleIds = requestData.roleIds.join(',')
          convertDateToString(requestData)
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            delete requestData.repassword
            requestData.password = CryptoJS.MD5("powerrichEeds" + CryptoJS.MD5(requestData.password).toString().substring(5)).toString()
            addUser(requestData).then((res) => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getListAndShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.userId = this.curId
            updateUser(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getListAndShow()
              this.dialogFormVisible = false
            })
          }
        } else {
          return false
        }
      })
    }
  },
  mounted () {
    this.getListAndShow()
    getRoleList({
      page: 1,
      pageSize: 10000,
    }).then((res) => {
      this.roleTypeOpts = res.data.queryResult
    })
  }
}
</script>

<style lang="scss" scoped>
.user-manage-wrapper {
  height: calc(100vh - 180px);
  background-color: #ffffff;
  padding: 15px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  border-radius: 3px;
  .el-form.dialog-form-comot {
    /deep/.el-form-item {
      .el-cascader,.el-select {
        width: 100%;
      }
      .el-date-editor.el-input, .el-date-editor.el-input__inner {
        width: 100%;
      }
      .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
  }
  .el-pagination.paging-self {
    margin-top: 20px;
    float: right;
  }
  .el-tree {
    /deep/.el-tree-node__content>.el-checkbox {
      margin-right: 8px;
    }
  }
}
</style>
